package com.laot.search.manager;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laot.search.datasource.DataSourceRegistry;
import lombok.extern.slf4j.Slf4j;
import org.laot.seacher_master.model.common.ErrorCode;
import org.laot.seacher_master.model.datasource.DataSource;
import org.laot.seacher_master.model.dto.search.SearchRequest;
import org.laot.seacher_master.model.enums.SearchTypeEnum;
import org.laot.seacher_master.model.exception.BusinessException;
import org.laot.seacher_master.model.vo.SearchTaskVO;
import org.laot.seacher_master.model.vo.SearchVO;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author laoT
 * 搜索门面
 */
@Component
@Slf4j
public class SearchFacade {
    @Resource
    private DataSourceRegistry dataSourceRegistry;

    public SearchVO searchAll(SearchRequest searchRequest, HttpServletRequest request) {
        String type = searchRequest.getType();
        SearchTypeEnum searchTypeEnum = SearchTypeEnum.getEnumByValue(type);
        String searchText = searchRequest.getSearchText();

        long current = searchRequest.getCurrent();
        long pageSize = searchRequest.getPageSize();
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (searchTypeEnum == null) {
            List<SearchTaskVO> taskList = new ArrayList<>();
            Map<String, DataSource> dataSourceMap = dataSourceRegistry.getDataSourceMap();
            //遍历所有数据源
            for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
                DataSource dataSource = entry.getValue();
                String key = entry.getKey();
                CompletableFuture<Page> searchTask = CompletableFuture.supplyAsync(() -> {
                    RequestContextHolder.setRequestAttributes(sra, true);
                    return dataSource.doSearch(searchText, current, pageSize);
                });
                SearchTaskVO searchTaskVO = new SearchTaskVO();
                searchTaskVO.setKey(key);
                searchTaskVO.setTaskPage(searchTask);
                taskList.add(searchTaskVO);
            }
            //将所有的任务转化为数组
            CompletableFuture<Page>[] array = taskList.stream()
                    .map(SearchTaskVO::getTaskPage)
                    .collect(Collectors.toList())
                    .toArray(new CompletableFuture[taskList.size()]);
            //执行任务
            CompletableFuture.allOf(array).join();
            SearchVO searchVO = new SearchVO();
            searchVO.setDataMap(new HashMap<>());
            //遍历所有任务
            for (SearchTaskVO searchTaskVO : taskList) {
                CompletableFuture<Page> taskPage = searchTaskVO.getTaskPage();
                String key = searchTaskVO.getKey();
                try {
                    searchVO.getDataMap().put(key,taskPage.get().getRecords());
                }catch (Exception e){
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR,"获取并发查询的数据时发生错误，原因是："+e.getMessage());
                }
            }
            return searchVO;
        } else {
            DataSource<?> dataSource = dataSourceRegistry.getDataSource(searchTypeEnum.getBeanName());
            Page<?> page = dataSource.doSearch(searchText, current, pageSize);
            SearchVO searchVO = new SearchVO();
            Map<String,Object> map = new HashMap<>();
            map.put(searchTypeEnum.getBeanName(),page.getRecords());
            searchVO.setDataMap(map);
            return searchVO;
        }
    }
}
